<template>
    <div>
        <el-card>
            <div style="margin-bottom: 16px;">
                <el-button type="primary" @click="handleAddProduct"><el-icon>
                        <CirclePlus />
                    </el-icon> 商品上架</el-button>
            </div>
            <el-form :inline="true" v-model="searchForm" style="margin-bottom: 16px;">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.title" placeholder="商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-cascader v-model="searchForm.categoryIds" :options="categories" :props="{
                        checkStrictly: false,
                        value: 'id',
                        label: 'name',
                        children: 'children',
                        emitPath: true,
                        changeOnSelect: false
                    }" clearable placeholder="请选择商品分类" @change="handleSearch" @clear="handleSearch">
                    </el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="tableData" border v-loading="loading" style="width: 100%">
                <el-table-column prop="id" label="编号" width="80" align="center" />
                <el-table-column prop="title" label="商品名称" min-width="155" />
                <el-table-column prop="main_image" label="商品图片" width="100" align="center">
                    <template #default="scope">
                        <img v-if="scope.row.main_image" :src="scope.row.main_image"
                            style="width: 60px; height: 60px; object-fit: contain;" alt="商品图片" />
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="90" align="center">
                    <template #default="scope">￥{{ scope.row.price }}</template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" width="90" align="center" />
                <el-table-column prop="sales" label="销量" width="90" align="center" />
                <el-table-column prop="status" label="状态" width="90" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                            {{ scope.row.status === 1 ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="商品描述" min-width="150">
                    <template #default="scope">
                        <el-tooltip class="item" effect="dark"
                            :content="scope.row.description ? scope.row.description.replace(/<[^>]+>/g, '') : ''"
                            placement="top">
                            <span class="ellipsis-text">
                                {{ scope.row.description ? scope.row.description.replace(/<[^>]+>/g, '') : '' }}
                            </span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="315" align="center">
                    <template #default="scope">
                        <el-button size="default" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="default" :type="scope.row.status === 1 ? 'warning' : 'success'"
                            @click="handleStatusChange(scope.row)">
                            {{ scope.row.status === 1 ? '下架' : '上架' }}
                        </el-button>
                        <el-button size="default" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :total="total" @current-change="handlePageChange" @size-change="handleSizeChange"
                layout="total,sizes,prev,pager,next,jumper" style="margin-top:16px" />
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getProductList, updateProductStatus, deleteProduct } from '../../api/productList.js';
import { getCategoryTree } from '../../api/categoryList.js';
import { CirclePlus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
const router = useRouter()


// 响应式数据
const loading = ref(false);
const searchForm = ref({ title: '', categoryIds: [] });
const categories = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const tableData = ref<Product[]>([]);


interface Product {
    id: number;
    title: string;
    main_image: string;
    price: number;
    stock: number;
    sales: number;
    status: 0 | 1;
    description: string;
}
// 方法定义
const fetchProductList = async () => {
    loading.value = true;
    try {
        const params = {
            title: searchForm.value.title,
            categoryId: searchForm.value.categoryIds.length > 0
                ? searchForm.value.categoryIds[searchForm.value.categoryIds.length - 1]
                : null,
            page: currentPage.value,
            pageSize: pageSize.value
        };
        const data = await getProductList(params);
        if (data.code === 0) {
            tableData.value = data.data.list || [];
            total.value = data.data.total || 0;
        } else {
            // ElMessage.error(data.msg || '获取商品列表失败');
            tableData.value = [];
        }
    } catch {
        //ElMessage.error("获取商品列表失败");
    } finally {
        loading.value = false;
    }
};

const fetchCategoryList = async () => {
    try {
        const res = await getCategoryTree()
        if (res.code === 0) {
            function cleanCategroyChildren(list) {
                if (!Array.isArray(list)) return;
                list.forEach(item => {
                    if (Array.isArray(item.children)) {
                        if (item.children.length === 0) {
                            delete item.children;
                        } else {
                            cleanCategroyChildren(item.children);
                        }
                    }
                });
            }
            cleanCategroyChildren(res.data);
            categories.value = res.data;
        }
    } catch {
        ElMessage.error("获取商品分类失败");
    } finally {
        loading.value = false;
    }
};

const handleSearch = () => {
    currentPage.value = 1;
    fetchProductList();
};

const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    fetchProductList();
};

const handlePageChange = (page: number) => {
    currentPage.value = page;
    fetchProductList();
};
/**
 * 编辑商品（跳转编辑页）
 */
const handleEdit = (row: Product) => {
    router.push(`/product/edit/${row.id}`);
};

/**
 * 商品上架（跳转新增页）
 */
const handleAddProduct = () => {
    router.push('/product/edit');
};

/**
 * 商品上下架状态变更（新增核心功能）
 */
const handleStatusChange = async (row: Product) => {
    const targetStatus = row.status === 1 ? 0 : 1;
    const confirmText = targetStatus === 1 ? '上架' : '下架';    
    try {
        await ElMessageBox.confirm(
            `确定要将商品【${row.title}】${confirmText}吗？`,
            '操作确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        const res = await updateProductStatus({ id: row.id, status: targetStatus });
        console.log(res)
        
        if (res.code === 0) {
            ElMessage.success(`商品${confirmText}成功`);
            row.status = targetStatus as 0 | 1;
        } else {
            ElMessage.error(`商品${confirmText}失败：${res.msg}`);
        }
    } catch (err) {
        if ((err as Error).message !== 'cancel') {
            console.error(`商品${confirmText}异常:`, err);
            ElMessage.error(`商品${confirmText}失败，请重试`);
        }
    }
};

/**
 * 删除商品（新增核心功能）
 */
const handleDelete = async (row: Product) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除商品【${row.title}】吗？删除后不可恢复！`,
            '危险操作',
            {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'danger'
            }
        );

        const res = await deleteProduct(row.id);
        if (res.code === 0) {
            ElMessage.success('商品删除成功');
            fetchProductList();
        } else {
            ElMessage.error(`商品删除失败：${res.msg}`);
        }
    } catch (err) {
        if ((err as Error).message !== 'cancel') {
            console.error('商品删除异常:', err);
            ElMessage.error('商品删除失败，请重试');
        }
    }
};

onMounted(() => {
    fetchCategoryList();
    fetchProductList();
});
</script>

<style scoped>
.ellipsis-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}
</style>
